<?php

namespace App\Admin\Controllers;

use App\Models\Scene;
use App\Models\StayTime;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Illuminate\Support\MessageBag;

class StayTimeController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('游客停留时间');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(StayTime::class, function (Grid $grid) {
            $grid->actions(function ($actions) {
                $actions->disableView();
            });
            $grid->disableExport();
            $grid->disableFilter();
            $grid->id('ID')->sortable();
            $grid->scene_id('景区')->display(function ($val){
                return Scene::find($val)?Scene::where('is_docking',1)->pluck('title','id')[$val]:$val;
            });
            $grid->time('停留时长')->display(function ($val){
                return config('options.flow_stay')[$val];
            });
            $grid->percent('占比')->display(function ($val){
                return $val.'%';
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(StayTime::class, function (Form $form) {

            $form->select('scene_id','景区')->options(Scene::where('is_docking',1)->pluck('title','id'));
            $form->select('time','停留时长')->options(config('options.flow_stay'));
            $form->rate('percent','占比');
            $form->saving(function (Form $form) {
                $rate = $form->percent;
                $left = StayTime::where('scene_id',$form->scene_id)->sum('percent');
                if($rate+$left>100){
                    $error = new MessageBag([
                        'title'   => '错误',
                        'message' => '该景区停留时长占比超过100%',
                    ]);
                    return back()->with(compact('error'));
                }
            });
        });
    }
}
